package com.ekuaitu.kuaitu.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.media.WantuService;
import com.alibaba.sdk.android.media.upload.UploadListener;
import com.alibaba.sdk.android.media.upload.UploadTask;
import com.alibaba.sdk.android.media.utils.FailReason;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.bean.ComplaintsBean;
import com.ekuaitu.kuaitu.bean.ComplaintsTagBean;
import com.ekuaitu.kuaitu.bean.UploadImageBean;
import com.ekuaitu.kuaitu.utils.AppManager;
import com.ekuaitu.kuaitu.utils.CheckRegexUtils;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.ImageLoader;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.KuaituDialog;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.SDCardUtils;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.ekuaitu.kuaitu.utils.zxing.android.CaptureActivity;
import com.michael.selectimage.PhotoPickerActivity;
import com.umeng.analytics.MobclickAgent;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class ComplaintsActivity extends AppCompatActivity implements UploadListener, AMapLocationListener {

    @BindView(R.id.editText_license)
    EditText editTextLicense;
    @BindView(R.id.editText_compliant)
    EditText editTextCompliant;
    @BindView(R.id.flowLayout_complaints)
    TagFlowLayout mFlowLayout;
    @BindView(R.id.imageView_compliant)
    ImageView imageviewCompliant;
    @BindView(R.id.iv_scan_compliant)
    ImageView ivScanCompliant;
    @BindView(R.id.complaints_pic_cancel)
    ImageView complaintsPicCancel;
    @BindView(R.id.radioGroup_complaints)
    RadioGroup radioGroupComplaints;
    @BindView(R.id.layout_complaints)
    ScrollView layoutComplaints;
    @BindView(R.id.webView_compliants)
    WebView webViewCompliants;
    @BindView(R.id.button_complaints)
    RadioButton buttonComplaints;
    @BindView(R.id.button_question)
    RadioButton buttonQuestion;
    @BindView(R.id.progressBar)
    AutoLinearLayout progressBar;

    private static final int PICK_PHOTO = 200;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private String compliant;
    private Context mContext = this;
    private WantuService wantuService;
    private UploadListener mListener = this;
    private ComplaintsActivity activity = this;
    private String[] picTokenArray = new String[]{""};
    private String[] picKeyArray = new String[]{""};
    private int businessType = 0;
    private String orderId;
    private String licenseTag;
    private LatLng curPosition;
    private String tag = "";
    private List<ComplaintsTagBean.AttachmentBean> tagList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compliants);
        ButterKnife.bind(this);
        AppManager.getAppManager().addActivity(this);
        Intent intent = getIntent();
        businessType = intent.getIntExtra(IntentKey.INTENT_TRIP_MODE, 0);
        orderId = intent.getStringExtra(IntentKey.INTENT_ORDER_ID);
        licenseTag = intent.getStringExtra("licenseTag");
        initView();
        initData();
    }

    public void initView() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimaryWhite), 0, true);
        WantuService.enableHttpDNS();
        WantuService.enableLog();
        wantuService = WantuService.getInstance();
        wantuService.asyncInit(this);
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocationLatest(true);
        mLocationClient.setLocationOption(mLocationOption);
        radioGroupComplaints.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == buttonComplaints.getId()) {
                    buttonComplaints.setChecked(true);
                    buttonQuestion.setChecked(false);
                    layoutComplaints.setVisibility(View.VISIBLE);
                    webViewCompliants.setVisibility(View.GONE);
                } else {
                    buttonComplaints.setChecked(false);
                    buttonQuestion.setChecked(true);
                    webViewCompliants.setVisibility(View.VISIBLE);
                    layoutComplaints.setVisibility(View.GONE);
                    initWebView();
                }
            }
        });

    }

    private void initWebView() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimaryWhite), 0, true);
        webViewCompliants.getSettings().setJavaScriptEnabled(true);
        webViewCompliants.getSettings().setUseWideViewPort(true);//设置此属性，可任意比例缩放
        webViewCompliants.getSettings().setLoadWithOverviewMode(true);
        //解决图片不显示
        webViewCompliants.getSettings().setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webViewCompliants.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webViewCompliants.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        if (businessType == 1) {
            webViewCompliants.loadUrl(UrlConstant.Request.FEEDBACK_CAR);
        } else {
            webViewCompliants.loadUrl(UrlConstant.Request.FEEDBACK_BIKE);
        }
    }

    private void initData() {

        editTextLicense.setText(licenseTag);
        if (businessType == 1) {
            ivScanCompliant.setVisibility(View.GONE);
        }
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getComplaintsTag(MyApplication.getInstance().getRequestFieldMap(), businessType + "").enqueue(new Callback<ComplaintsTagBean>() {
            @Override
            public void onResponse(Call<ComplaintsTagBean> call, Response<ComplaintsTagBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        if (response.body().getAttachment() != null) {
                            tagList = response.body().getAttachment();
                            int tagsCount = tagList.size();
                            String[] tags = new String[tagsCount];
                            for (int i = 0; i < tagsCount; i++) {
                                tags[i] = tagList.get(i).getTagName();
                            }
                            initFlowLayout(tags);
                        }
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ComplaintsTagBean> call, Throwable t) {
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private Set<Integer> selectPosSetAll;

    private void initFlowLayout(final String[] tags) {
        final LayoutInflater mInflater = LayoutInflater.from(mContext);
        mFlowLayout.setAdapter(new TagAdapter<String>(tags) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) mInflater.inflate(R.layout.item_flowlayout_complaints, mFlowLayout, false);
                tv.setText(s);
                return tv;
            }
        });
        mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                return true;
            }
        });


        mFlowLayout.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
            @Override
            public void onSelected(Set<Integer> selectPosSet) {
                selectPosSetAll = selectPosSet;
                tag = "";
                if (selectPosSet.size() != 0) {
                    for (Integer index : selectPosSet) {
                        tag = tag + tagList.get(index).getTagId() + ",";
                    }
                }
            }
        });

        //  mAdapter.setSelectedList(1,3,5,7,8,9);
    }


    @OnClick({R.id.return_compliant, R.id.textView_commit_compliant, R.id.imageView_compliant, R.id.hotLine_compliant, R.id.iv_scan_compliant, R.id.complaints_pic_cancel})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.return_compliant:
                finish();
                break;
            case R.id.textView_commit_compliant:

                compliant = editTextCompliant.getText() + "";
                if (TextUtils.isEmpty(tag)) {
                    ToastCompat.makeText(mContext, "请选择问题类型", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (isMustPhoto()) {
                    if (picKeyArray[0].equals("") || picKeyArray[0] == null) {
                        ToastCompat.makeText(mContext, "请您上传照片", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                progressBar.setVisibility(View.VISIBLE);
                if (curPosition == null) {
                    startLocation();
                } else {
                    commitCompliant();
                }
                break;
            case R.id.imageView_compliant: {
                //跳转图片选择
                Intent intent = new Intent(ComplaintsActivity.this, PhotoPickerActivity.class);
                intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);
                intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_SINGLE);
                intent.putExtra(PhotoPickerActivity.EXTRA_CROP_IMAGE, false);
                //intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, PhotoPickerActivity.DEFAULT_NUM);
                startActivityForResult(intent, PICK_PHOTO);
                break;
            }
            case R.id.hotLine_compliant:
                final KuaituDialog kuaituDialog1 = new KuaituDialog(mContext);
                kuaituDialog1.setTitle(getString(R.string.dialogTitle));
                kuaituDialog1.setMessage("是否拨打客服电话" + MyApplication.getInstance().getHotLine());
                kuaituDialog1.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse("tel:" + MyApplication.getInstance().getHotLine()));
                        startActivity(intent);
                        kuaituDialog1.dismiss();
                    }
                });
                kuaituDialog1.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        kuaituDialog1.dismiss();
                    }
                });
                kuaituDialog1.show();
                break;
            case R.id.iv_scan_compliant:
                Intent intent = new Intent(this, CaptureActivity.class);
                intent.putExtra("title", "意见反馈");
                startActivityForResult(intent, Constants.REQUEST_SCAN_COMPLIANT);
                break;
            case R.id.complaints_pic_cancel:
                imageviewCompliant.setImageDrawable(null);
                complaintsPicCancel.setVisibility(View.GONE);
                break;
        }
    }

    private boolean isMustPhoto() {
        if (selectPosSetAll.size() != 0) {
            for (Integer index : selectPosSetAll) {
                if (tagList.get(index).isUploadPhoto()) {
                    return true;
                }
            }
        }
        return false;
    }


    private void commitCompliant() {
        licenseTag = editTextLicense.getText() + "";
        if (orderId == null) {
            orderId = "";
        }
        if (compliant == null) {
            compliant = "";
        }
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).commitComplaints(MyApplication.getInstance().getRequestFieldMap(), compliant, picKeyArray[0], businessType + "",
                orderId, licenseTag, curPosition.latitude + "", curPosition.longitude + "", tag).enqueue(new Callback<ComplaintsBean>() {
            @Override
            public void onResponse(Call<ComplaintsBean> call, Response<ComplaintsBean> response) {
                progressBar.setVisibility(View.GONE);
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        final KuaituDialog kuaituDialog = new KuaituDialog(ComplaintsActivity.this);
                        kuaituDialog.setTitle(getString(R.string.dialogTitle));
                        kuaituDialog.setSingleButton(true);
                        if (businessType == 2 && !orderId.equals("")) { //单车，骑行中反馈问题
                            kuaituDialog.setMessage("感谢您的反馈，我们会及时处理，请尽快关闭车锁，还车结束行程。");
                        } else {
                            kuaituDialog.setMessage("感谢您的反馈，我们会及时处理");
                        }
                        kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                kuaituDialog.dismiss();
                                finish();
                            }
                        });
                        kuaituDialog.setCancelable(false);
                        kuaituDialog.show();
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ComplaintsBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void startLocation() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, Constants.READ_LOCATION_PERMISSION_REQUEST);
            } else {
                mLocationClient.startLocation();
            }
        } else {
            mLocationClient.startLocation();
        }

    }

    private void uploadImage(final File picFile) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).uploadImage(MyApplication.getInstance().getRequestFieldMap(), "jpg", "", "", "", "1", "0", "kuaitu").enqueue(new Callback<UploadImageBean>() {
            @Override
            public void onResponse(Call<UploadImageBean> call, Response<UploadImageBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        picTokenArray[0] = response.body().getAttachment().getToken();
                        picKeyArray[0] = response.body().getAttachment().getKey();
                        wantuService.upload(picFile, mListener, picTokenArray[0]);
                    } else {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<UploadImageBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onUploading(UploadTask uploadTask) {
    }

    @Override
    public void onUploadFailed(UploadTask uploadTask, FailReason failReason) {
        Message message = new Message();
        message.arg1 = 5;
        Bundle b = new Bundle();
        b.putString("failReason", failReason.getMessage());
        message.setData(b);
        handler.sendMessage(message);
    }

    @Override
    public void onUploadComplete(UploadTask uploadTask) {
        Message message = new Message();
        message.arg1 = 4;
        Bundle b = new Bundle();
        message.setData(b);
        handler.sendMessage(message);
    }

    @Override
    public void onUploadCancelled(UploadTask uploadTask) {
        Message message = new Message();
        message.arg1 = 6;
        Bundle b = new Bundle();
        message.setData(b);
        handler.sendMessage(message);
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            curPosition = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            commitCompliant();
        } else {
            progressBar.setVisibility(View.GONE);
            ToastCompat.makeText(mContext, "获取位置信息失败，请重试...", Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }


    private File originalFile;
    private File compressFile;
    private ArrayList<String> pics = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_SCAN_COMPLIANT && resultCode == Constants.RESULT_SCAN) {
            //扫码后的字符串
            String code = data.getStringExtra("codedContent");
            if (code.length() == 52 && code.substring(0, 44).equals(UrlConstant.Request.QR_URL) && CheckRegexUtils.checkQRCode(code.substring(44, 52))) {
                editTextLicense.setText(code.substring(44, 52));
            } else {
                ToastCompat.makeText(mContext, "请扫描快兔单车的二维码", Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
            }
        } else if (requestCode == PICK_PHOTO) {   //获得图片后
            if (resultCode == Activity.RESULT_OK) {
                final ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                if (result == null || result.size() == 0) {
                    return;
                }
                originalFile = new File(result.get(0));
                Luban.with(this)
                        .load(originalFile)  //传入要压缩的图片
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                Message message = new Message();
                                message.arg1 = 1;
                                Bundle b = new Bundle();
                                b.putString("originalPath", result.get(0));
                                message.setData(b);
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onSuccess(File file) {
                                Message message = new Message();
                                message.arg1 = 2;
                                Bundle b = new Bundle();
                                b.putString("compressPath", file.getAbsolutePath());
                                message.setData(b);
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onError(Throwable e) {
                                Message message = new Message();
                                message.arg1 = 3;
                                handler.sendMessage(message);
                            }
                        }).launch();    //启动压缩

            }
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case 1:
                    progressBar.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    //成功压缩
                    String pathName = msg.getData().getString("compressPath");
                    pics.add(pathName);
                    //上传图片
                    compressFile = new File(pathName);
                    uploadImage(compressFile);
                    break;
                case 3:
                    //压缩失败
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, "图片压缩失败，请重试", Toast.LENGTH_LONG).show();
                    break;
                case 4: //上传成功
                    progressBar.setVisibility(View.GONE);
                    ImageLoader.getInstance().displayImage(mContext, compressFile, imageviewCompliant);
                    break;
                case 5:
                    //上传失败
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, msg.getData().getString("failReason"), Toast.LENGTH_SHORT).show();
                    break;
                case 6:
                    //上传取消
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, "图片上传取消", Toast.LENGTH_SHORT).show();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (pics != null && pics.size() != 0) {
            for (int i = 0; i < pics.size(); i++) {
                SDCardUtils.removeFileFromSDCard(pics.get(i));
            }
        }
    }
}
